package edu.johnpank.libassistant.config

import edu.johnpank.libassistant.enums.Role
import edu.johnpank.libassistant.services.UserDetailServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.NoOpPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder


@EnableWebSecurity
class SecurityConfig(
    @Autowired
    val userService: UserDetailServiceImpl
): WebSecurityConfigurerAdapter() {

    //Настройка авторизации
    protected override fun configure(http: HttpSecurity){
        http.authorizeRequests()
            .antMatchers("/admin/*").hasRole("ADMIN")
            .antMatchers("/librarian/*").hasRole("LIBRARIAN")
            .antMatchers("/reader/*").hasRole("READER")
//            .antMatchers("/admin").hasAuthority(Role.ROLE_ADMIN.name)   //only for admin
//            .antMatchers("/librarian").hasAuthority(Role.ROLE_LIBRARIAN.name)   //only for librarian
            .antMatchers("/", "/auth/login", "/error", "/auth/registration", "/about").permitAll()
//            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/auth/login")
            .loginProcessingUrl("/process_login")
            .defaultSuccessUrl("/main")
            .failureUrl("/auth/login?error")
            .and()
            .logout().logoutUrl("/logout").logoutSuccessUrl("/main")

    }

    //Настройка аутентификации
    protected override fun configure(auth: AuthenticationManagerBuilder) {
        auth.userDetailsService(userService).passwordEncoder(getPasswordEncoder())
    }

    @Bean
    fun getPasswordEncoder(): PasswordEncoder{
        return BCryptPasswordEncoder()
    }

    // hash for "admin":$2a$12$/ohuMD1nCywqX7E9m1kQVeAX5S1Bv9ASE5f3734hsszS.RWQgWd2i

}